<template>
  <div class="app-container">
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleOpenAddDialog()"><i-ep-plus />新增</el-button>
        <el-button type="danger" :disabled="selectionIds.length === 0" @click="handleDelete()"><i-ep-delete />删除
        </el-button>
      </template>

      <el-table ref="areaTreeTableRef" v-loading="loading" :data="areaData" row-key="id" lazy :load="loadTreeData"
        :tree-props="{ children: 'children', hasChildren: 'has_children' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="名称" min-width="150" />
        <el-table-column prop="pinyin" label="拼音简写" min-width="150" align="center" />
        <el-table-column prop="ccode" label="代码" min-width="150" align="center" />
        <el-table-column label="状态" prop="enabled" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.enabled" :active-value="1" :inactive-value="0"
              @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="create_time" width="155">
          <template #default="scope">
            {{ formatDate(scope.row.create_ms) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button type="primary" link size="small" @click.stop="handleOpenAddDialog(scope.row)"><i-ep-plus />新增
            </el-button>
            <el-button type="primary" link size="small" @click.stop="handleOpenEditDialog(scope.row)"><i-ep-edit />编辑
            </el-button>
            <el-button type="danger" link size="small" @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--表单数据-->
    <Form ref="areaFormRef" v-model="dialog.visible" :title="dialog.title" :area-item="selectedItem"
      @close="handleCloseDialog" @submit="handleDialogSubmit" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Area",
  inheritAttrs: false,
})

import AreaAPI, { AreaVO } from "@/api/area"
import { buildTree, formatDate } from "@/utils";
import Form from "./form.vue";

const areaTreeTableRef = ref()
const searchFormRef = ref(ElForm)

const loading = ref(false)
const dialog = reactive({
  title: "新增",
  visible: false,
})
const selectionIds = ref<number[]>([])

const selectedItem = ref<AreaVO>()

const areaData = ref<AreaVO[]>()

const parentAreaData = ref<AreaVO[]>()

const queryCondition: QueryCondition = {
  and: []
}
const getAreaTree = () => {
  loading.value = true
  queryCondition.and = []
  queryCondition.and?.push({ field: 'id', op: '=', value: 0 })
  AreaAPI.query(queryCondition).then((res) => {
    if (res.status == 200) {
      areaData.value = res.data
    }
  }).finally(() => { loading.value = false })
}

onMounted(() => {
  getAreaTree()
})

const loadTreeData = (row: AreaVO, treeNode: unknown, resolve: (data: AreaVO[]) => void) => {
  console.log(treeNode)

  queryCondition.and = []
  queryCondition.and?.push({ field: 'pcode', op: '=', value: row.ccode })
  AreaAPI.query(queryCondition).then((res) => {
    if (res.status == 200) {
      resolve(res.data)
    }
  }).finally(() => { loading.value = false })
}


/** 查询 */
const handleQuery = () => {
  getAreaTree()
}

/** 重置查询 */
const handleResetQuery = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  handleQuery()
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  selectionIds.value = selection.map((item: any) => item.id)
}


/** 改变状态 */
const handleStatusChange = (row: AreaVO) => {
  AreaAPI.update(row).then((res) => {
    if (res.status === 200) {
      ElMessage.success("更新状态成功")
      handleQuery()
    }
  })
}


/**
 * 打开新增弹窗
 *
 */
const handleOpenAddDialog = (row: AreaVO = {}) => {
  dialog.title = "新增"
  if (row.id) {
    selectedItem.value = {
      pcode: row.ccode,

    }
  }

  console.log(areaTreeTableRef.value)

  dialog.visible = true
}
/**
 * 打开编辑弹窗
 */
const handleOpenEditDialog = (row: AreaVO = {}) => {
  dialog.title = "修改"
  selectedItem.value = Object.assign({}, row)
  dialog.visible = true
}


// 删除菜单
const handleDelete = (areaId?: number) => {
  const areaIds = areaId ? [areaId] : selectionIds.value
  if (!areaIds) {
    ElMessage.warning("请勾选删除项")
    return
  }
  ElMessageBox.confirm("确认删除已选中的及其子么?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    const deleteCondition: QueryCondition = {
      "_cond": { and: [{ field: "id", op: "in", value: areaIds }] }
    }
    AreaAPI.deleteByCondition(deleteCondition).then((res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功")
        handleQuery()
      }
    }).finally(() => {
      loading.value = false
    })
  })
}

/** 提交表单 */
const handleDialogSubmit = () => {
  dialog.visible = false
  handleQuery()
}

/** 关闭弹窗 */
const handleCloseDialog = () => {
  dialog.visible = false
}

</script>
